<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";
import { generateColor } from "@/utils/color";
export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "550px",
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
    chartData: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "category");
      this.setOptions(this.chartData);
    },
    setOptions({ courseName, data }) {
      if (courseName && data) {
        let newData = courseName.map((item, idx) => {
          return {
            value: data[idx],
            // 设置单个柱子的样式
            itemStyle: {
              color: generateColor(item),
              shadowColor: generateColor(item),
              borderType: "dashed",
              opacity: 0.6,
            },
          };
        });

        this.chart.setOption({
          xAxis: {
            data: courseName,
            axisTick: {
              show: false,
            },
          },
          grid: {
            left: 10,
            right: 10,
            bottom: 20,
            top: 30,
            containLabel: true,
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
            },
            padding: [5, 10],
          },
          yAxis: {
            axisTick: {
              show: false,
            },
          },

          series: [
            {
              type: "bar",
              data: newData,
              itemStyle: {
                barBorderRadius: 7,
                shadowBlur: 3,
              },
              barWidth: "20%",
            },
          ],
        });
      }
    },
  },
};
</script>
